<template>
    <div class="image-view-container">
        <!-- 顶部标题和返回按钮 -->
        <div class="header">
            <!-- 第一行：返回按钮靠左 -->
            <div class="header-row">
                <el-button type="primary" icon="Back" @click="goBack" class="back-btn">
                    <i class="el-icon-back"></i> 返回文件列表
                </el-button>
            </div>
            
            <!-- 第二行：标题居中 -->
            <div class="header-row">
                <h2 class="header-title">图片查看 - {{ fileName }}</h2>
            </div>
        </div>

        <!-- 图片卡片展示区 -->
        <div class="image-grid">
            <el-row :gutter="20">
                <el-col v-for="(image, index) in imageList" :key="index" :xs="24" :sm="12" :md="8" :lg="6">
                    <el-card class="image-card" shadow="hover">
                        <!-- 第一部分：图片展示 -->
                        <div class="image-container">
                            <el-image :src="getImageUrl(image.image_path)" fit="contain">
                                <template #error>
                                    <div class="image-error">
                                        <i class="el-icon-picture-outline"></i>
                                        <p>图片加载失败</p>
                                    </div>
                                </template>
                            </el-image>
                        </div>

                        <!-- 第二部分：图片信息 -->
                        <div class="image-info">
                            <div class="info-item">
                                <span class="label">创建时间:</span>
                                <span class="value">{{ formatDate(image.create_date) }}</span>
                            </div>
                            <div class="info-item">
                                <span class="label">向量ID:</span>
                                <span class="value">{{ image.vector_id }}</span>
                            </div>
                        </div>

                        <!-- 第三部分：操作按钮 -->
                        <div class="image-actions">
                            <el-button type="primary" size="small" @click="showDescDialog(image.image_desc)"
                                :disabled="!image.image_desc">
                                <i class="el-icon-document"></i> 查看描述
                            </el-button>

                            <!-- 编辑按钮 -->
                            <el-button type="success" size="small" @click="openEditDialog(image)"
                                :disabled="editingId === image.vector_id"
                                :loading="editingId === image.vector_id"
                            >
                                <i class="el-icon-edit"></i> 
                                {{ editingId === image.vector_id ? '编辑中...' : '编辑' }}
                            </el-button>

                            <!-- 修改：图片预览按钮 -->
                            <el-button type="primary" size="small" @click="openImagePreview(image)">
                                <i class="el-icon-view"></i> 图片预览
                            </el-button>

                             <el-button type="danger" size="small" @click="deleteImage(image)">
                                <i class="el-icon-delete"></i> 删除
                            </el-button>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <!-- 分页组件 -->
        <div class="pagination-container">
            <el-pagination background layout="prev, pager, next, sizes, total" :total="totalItems" :page-size="pageSize"
                :current-page="currentPage" @size-change="handleSizeChange" @current-change="handlePageChange" />
        </div>

        <!-- 图片描述弹窗 -->
        <el-dialog v-model="descDialogVisible" title="图片描述" width="50%" :close-on-click-modal="true">
            <div class="desc-content">
                <p v-if="currentDesc">{{ currentDesc }}</p>
                <p v-else class="no-desc">该图片暂无描述信息</p>
            </div>
            <template #footer>
                <el-button @click="descDialogVisible = false">关闭</el-button>
                <el-button type="primary" @click="descDialogVisible = false">确定</el-button>
            </template>
        </el-dialog>

        <!-- 新增：图片预览弹窗 -->
        <el-dialog v-model="previewDialogVisible" title="图片预览" width="90%" top="5vh" class="image-preview-dialog"
            :close-on-click-modal="true" :lock-scroll="false">
            <div class="preview-content">
                <img :src="currentPreviewImage" class="preview-image" :alt="currentPreviewImageName" @load="onImageLoad"
                    @error="onImageError" />
            </div>
            <template #footer>
                <div class="preview-footer">
                    <span class="image-info">{{ currentPreviewImageName }} - 原始尺寸: {{ imageDimensions.width }} × {{
                        imageDimensions.height }}px</span>
                    <el-button @click="previewDialogVisible = false">关闭</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 新增：编辑描述弹窗 -->
    <el-dialog 
      v-model="editDialogVisible" 
      :title="`编辑图片描述 - ${currentEditItem.file_name || ''}`"
      width="600px"
      top="5vh"
      class="edit-desc-dialog"
      :close-on-click-modal="false"
      :before-close="handleEditDialogClose"
    >
      <div class="edit-dialog-content">
        <div class="edit-header">
          <div class="file-info">
            <span class="label">文件名称:</span>
            <span class="value">{{ currentEditItem.file_name }}</span>
          </div>
          <div class="vector-info">
            <span class="label">向量ID:</span>
            <span class="value vector-id">{{ currentEditItem.vector_id }}</span>
          </div>
        </div>
        
        <div class="edit-form">
          <el-form 
            :model="editForm" 
            ref="editFormRef" 
            label-width="80px"
            :rules="editRules"
          >
            <el-form-item label="图片描述" prop="image_desc">
              <el-input
                v-model="editForm.image_desc"
                type="textarea"
                :rows="6"
                placeholder="请输入图片描述"
                resize="vertical"
                show-word-limit
                maxlength="500"
                class="desc-textarea"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <template #footer>
        <div class="edit-dialog-footer">
          <el-button 
            @click="handleEditCancel" 
            :disabled="editLoading"
          >
            取消
          </el-button>
          <el-button 
            type="primary" 
            @click="handleEditConfirm"
            :loading="editLoading"
          >
            {{ editLoading ? '提交中...' : '确认编辑' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted,nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage,ElMessageBox } from 'element-plus'
import axios from 'axios'
import { getImageList, deleteSingleImage ,updateImageDesc} from '@/api/image'
// 获取路由实例
const route = useRoute()
const router = useRouter()

// 组件数据
const imageList = ref([])
const fileName = ref('')
const totalItems = ref(0)
const currentPage = ref(1)
const pageSize = ref(12)
const loading = ref(false)

// 描述弹窗相关状态
const descDialogVisible = ref(false)
const currentDesc = ref('')

// 新增：图片预览弹窗相关状态
const previewDialogVisible = ref(false)
const currentPreviewImage = ref('')
const currentPreviewImageName = ref('')
const imageDimensions = ref({ width: 0, height: 0 })


// 编辑相关数据
const editDialogVisible = ref(false)
const currentEditItem = ref({})
const editForm = reactive({
  image_desc: ''
})
const editFormRef = ref(null)
const editLoading = ref(false)
const editingId = ref(null) // 当前正在编辑的项目ID

// 表单验证规则
const editRules = reactive({
  image_desc: [
    { required: true, message: '图片描述不能为空', trigger: 'blur' },
    { min: 1, max: 500, message: '描述长度应在 1 到 500 个字符之间', trigger: 'blur' }
  ]
})


// 组件挂载时获取数据
onMounted(() => {
    fetchImageData()
})

// 获取图片数据
const fetchImageData = async () => {
    loading.value = true
    try {
        const response = await getImageList(
            route.params.file_id,
            currentPage.value,
            pageSize.value)
        if (response.data.statusCode === 200) {
            imageList.value = response.data.data.list
            totalItems.value = response.data.data.total_items
            if (imageList.value.length > 0) {
                fileName.value = route.query.file_name || imageList.value[0].file_name
            }
        }
    } catch (error) {
        console.error('获取图片数据失败:', error)
        ElMessage.error('获取图片数据失败，请稍后重试')
    } finally {
        loading.value = false
    }
}

// 处理图片路径
const getImageUrl = (path) => {
    // 从环境变量读取基础URL，并确保路径格式正确
    const baseUrl = import.meta.env.VITE_API_BASE_URL;
    // 处理路径中的反斜杠，并确保路径不以斜杠开头，避免拼接出双斜杠
    const normalizedPath = path.replace(/^[\\/]+/, '').replace(/\\/g, '/');
    return `${baseUrl}/${normalizedPath}`;
}

// 格式化日期
const formatDate = (dateString) => {
    return new Date(dateString).toLocaleString()
}

// 分页大小改变
const handleSizeChange = (size) => {
    pageSize.value = size
    currentPage.value = 1
    fetchImageData()
}

// 页码改变
const handlePageChange = (page) => {
    currentPage.value = page
    fetchImageData()
}

// 返回文件列表
const goBack = () => {
    router.go(-1)
}

// 显示描述弹窗
const showDescDialog = (desc) => {
    currentDesc.value = desc || '该图片暂无描述信息'
    descDialogVisible.value = true
}

// 新增：打开图片预览弹窗
const openImagePreview = (image) => {
    currentPreviewImage.value = getImageUrl(image.image_path)
    currentPreviewImageName.value = image.file_name
    imageDimensions.value = { width: 0, height: 0 } // 重置尺寸
    previewDialogVisible.value = true
}

// 新增：图片加载完成回调
const onImageLoad = (event) => {
    const img = event.target
    imageDimensions.value = {
        width: img.naturalWidth,
        height: img.naturalHeight
    }
}

// 新增：图片加载错误回调
const onImageError = () => {
    ElMessage.error('图片加载失败，请检查网络连接或图片路径')
    imageDimensions.value = { width: 0, height: 0 }
}

// 删除图片（占位）
const deleteImage = async (image) => {
  try {
      await ElMessageBox.confirm(`确定要删除图片吗？此操作不可恢复`, '确认删除',
        {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'delete-confirm-btn',
        cancelButtonClass: 'delete-cancel-btn'
      }
    )
    
    const response = await deleteSingleImage(image.vector_id)
    
    if (response.data.statusCode === 200) {
      // 核心代码：从当前列表中移除已删除项
      const index = imageList.value.findIndex(item => item.vector_id === image.vector_id)
      if (index !== -1) {
        imageList.value.splice(index, 1) // 直接操作数组，Vue会自动更新视图
        totalItems.value -= 1 // 更新总数
      }
      
      ElMessage.success('删除成功')
      
      // 处理删除后当前页为空的情况
      if (imageList.value.length === 0 && currentPage.value > 1) {
        currentPage.value -= 1
        await fetchImageData() // 返回前一页
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 打开编辑弹窗
const openEditDialog = (image) => {
  currentEditItem.value = image
  editForm.image_desc = image.image_desc || ''
  editingId.value = image.vector_id
  editDialogVisible.value = true
  
  // 下次DOM更新后自动聚焦到文本区域
  nextTick(() => {
    if (editFormRef.value) {
      editFormRef.value.clearValidate()
    }
  })
}

// 处理编辑弹窗关闭
const handleEditDialogClose = (done) => {
  if (editLoading.value) {
    ElMessage.info('正在提交修改，请稍候...')
    return
  }
  
  if (editForm.image_desc !== currentEditItem.value.image_desc) {
    ElMessageBox.confirm('描述内容已修改，是否放弃修改？', '提示', {
      confirmButtonText: '放弃修改',
      cancelButtonText: '继续编辑',
      type: 'warning'
    }).then(() => {
      done()
      resetEditForm()
    }).catch(() => {
      // 用户选择继续编辑，不关闭弹窗
    })
  } else {
    done()
    resetEditForm()
  }
}

// 取消编辑
const handleEditCancel = () => {
  if (editForm.image_desc !== currentEditItem.value.image_desc) {
    ElMessageBox.confirm('确定要放弃修改吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      editDialogVisible.value = false
      resetEditForm()
    })
  } else {
    editDialogVisible.value = false
    resetEditForm()
  }
}

// 确认编辑
const handleEditConfirm = async () => {
  try {
    // 表单验证
    if (!editFormRef.value) return
    
    const valid = await editFormRef.value.validate()
    if (!valid) return
    
    editLoading.value = true
    
    // 调用更新API
    const response = await updateImageDesc(
      currentEditItem.value.vector_id,
      editForm.image_desc
    )
    
    if (response.data.statusCode === 200) {
      // 更新本地数据
      const index = imageList.value.findIndex(
        item => item.vector_id === currentEditItem.value.vector_id
      )
      if (index !== -1) {
        imageList.value[index].image_desc = editForm.image_desc
      }
      
      ElMessage.success('图片描述更新成功')
      editDialogVisible.value = false
      resetEditForm()
    } else {
      ElMessage.error(`更新失败: ${response.data.message}`)
    }
  } catch (error) {
    console.error('更新图片描述失败:', error)
    if (error.response) {
      ElMessage.error(`更新失败: ${error.response.data.message || '服务器错误'}`)
    } else if (error.request) {
      ElMessage.error('网络连接失败，请检查网络设置')
    } else {
      ElMessage.error('更新操作失败，请稍后重试')
    }
  } finally {
    editLoading.value = false
  }
}

// 重置编辑表单
const resetEditForm = () => {
  editingId.value = null
  currentEditItem.value = {}
  editForm.image_desc = ''
  if (editFormRef.value) {
    editFormRef.value.clearValidate()
  }
}

</script>

<style scoped>
/* 原有样式保持不变 */
.image-view-container {
    padding: 20px;
    max-width: 1400px;
    margin: 0 auto;
}

.header {
    display: flex;
    flex-direction: column; /* 垂直排列 */
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
}

.header-row {
    display: flex;
    width: 100%;
}

/* 第一行：按钮靠左 */
.header-row:first-child {
    justify-content: flex-start;
    margin-bottom: 10px; /* 添加行间距 */
}

/* 第二行：标题居中 */
.header-row:last-child {
    justify-content: center;
}

.back-btn {
    margin-right: 0;
}

.header-title {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #303133;
    text-align: center;
}

.image-grid {
    margin-bottom: 30px;
}

.image-card {
    margin-bottom: 20px;
    transition: transform 0.3s, box-shadow 0.3s;
}

.image-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.1);
}

.image-container {
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f8f8f8;
    border-radius: 4px;
    overflow: hidden;
    margin-bottom: 15px;
}

.image-info {
    padding: 15px 0;
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;
    margin: 15px 0;
}

.info-item {
    display: flex;
    margin-bottom: 8px;
    font-size: 14px;
}

.label {
    font-weight: bold;
    color: #606266;
    min-width: 80px;
}

.value {
    color: #909399;
    flex: 1;
    word-break: break-all;
}

.image-actions {
    display: grid;
    grid-template-columns: repeat(2,  minmax(0, 1fr)); /* 创建4个等宽列 */
    gap: 8px;/* 按钮间距 */
    margin-top: 15px;
    align-items: stretch; /* 关键2：按钮在单元格内垂直填充满 */

    justify-items:end;
}

/* 按钮统一样式 */
.image-actions .el-button {
    width: 100%;  /*占满整个网格单元格*/
    padding: 8px 5px; /* 统一内边距 */
    font-size: 13px; /* 统一字体大小 */
    white-space: nowrap; /* 防止文字换行 */
    overflow: hidden;
    text-overflow: ellipsis; /* 文字过长显示省略号 */
    box-sizing: border-box; /* 确保内边距不影响总宽度 */
    min-width: 0; /* 关键修改：允许按钮收缩 */
    border-radius: 4px; /* 可选：统一按钮圆角，视觉更整齐 */
}

/* 响应式设计 - 小屏幕 */
@media (max-width: 768px) {
    .image-actions {
        grid-template-columns: repeat(2, 1fr); /* 小屏幕改为2列 */
    }
    
    .image-actions .el-button {
        font-size: 12px; /* 小屏幕字体稍小 */
        padding: 6px 4px; /* 小屏幕内边距稍小 */
    }
}

/* 响应式设计 - 超小屏幕 */
@media (max-width: 480px) {
    .image-actions {
        grid-template-columns: 1fr; /* 超小屏幕改为1列 */
    }
}


.pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

/* 新增：图片预览弹窗样式 */
.image-preview-dialog {
    max-width: 95vw;
}

.image-preview-dialog .el-dialog__body {
    padding: 0;
    max-height: 80vh;
    overflow: hidden;
}

.preview-content {
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: #f5f5f5;
    display: flex;
    justify-content: center;
    align-items: flex-start;
    min-height: 400px;
}

.preview-image {
    max-width: none;
    height: auto;
    display: block;
    margin: 0 auto;
}

.preview-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}

.image-info {
    font-size: 14px;
    color: #666;
}


/* 新增：编辑弹窗样式 */
.edit-desc-dialog .el-dialog__body {
  padding: 0;
}

.edit-dialog-content {
  padding: 20px;
}

.edit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 4px;
}

.file-info, .vector-info {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.file-info .label, .vector-info .label {
  font-weight: 600;
  color: #606266;
  min-width: 70px;
  margin-right: 8px;
}

.file-info .value, .vector-info .value {
  color: #909399;
}

.vector-id {
  font-family: monospace;
  font-size: 12px;
}

.edit-form {
  margin-top: 20px;
}

.desc-textarea {
  font-family: inherit;
}

.desc-textarea :deep(.el-textarea__inner) {
  font-family: inherit;
  line-height: 1.5;
}

.edit-dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}


/* 响应式调整 */
@media (max-width: 768px) {
    .image-preview-dialog {
        width: 95% !important;
    }

    .preview-footer {
        flex-direction: column;
        gap: 10px;
        align-items: flex-start;
    }

    .image-actions {
        grid-template-columns: 1fr;
    }
}

/* 删除按钮样式优化 */
.delete-confirm-btn {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.delete-cancel-btn {
  color: #909399;
}

.vector-id {
  font-family: monospace;
  font-size: 12px;
  word-break: break-all;
}

.empty-state {
  margin: 40px 0;
  text-align: center;
}

.loading-container {
  margin: 20px 0;
}
</style>